/*
 * $HeadURL: $
 * $Id: $
 * Copyright (c) 2011 by Ericsson, all rights reserved.
 */

package android.views;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.test.R;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 *
 * @author xyonton
 * @version $Revision: $
 */
public class HelloGridView extends Activity {
    /** Revision of the class */
    public static final String          _REV_ID_         = "$Revision: $";

    private static final String         TAG              = "HelloGridView";

    Toast                               toast;

    LinearLayout                        toastView;

    ImageView                           imageCodeProject;

    View                                layouthome, layoutimage, layoutDashboard;

    public static long                  screenWidth;

    public static long                  screenHeight;

    public static boolean               isphotoHome;

    public static int                   curPhotoPosition;

    //    public static String       imagePath = Environment.getExternalStorageDirectory() + File.separator + "DCIM"
    //                                                 + File.separator;
    public static String                imagePath        = File.separator + "sdcard" + File.separator + "DCIM"
                                                                 + File.separator;

    public static List<String>          imageList;

    private static GridView             gridview;

    private static ImageAdapter         imageAdapter;

    public static Bitmap                bitmap;

    public static int                   count;

    public static BitmapFactory.Options options;

    final private int                   groupHome        = 0;

    final private int                   groupPhoto       = 1;

    final private int                   menuSetWallpaper = Menu.FIRST;

    final private int                   menuDelete       = Menu.FIRST + 1;

    final private int                   menuAbout        = Menu.FIRST + 2;

    public void onCreate(Bundle savedInstanceState) {

        Log.e(TAG, "start onCreate~~~");

        super.onCreate(savedInstanceState);

        init();

        LayoutInflater inflater = getLayoutInflater();
        layouthome = inflater.inflate(R.layout.gridview, null);
        layoutimage = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
        layoutDashboard = inflater.inflate(R.layout.dashboard, null);

        setContentView(layouthome);

        gridview = (GridView) findViewById(R.id.gridview);
        imageAdapter = new ImageAdapter(this, imageList);
        gridview.setAdapter(imageAdapter);

        // Set the flag, now is open photohome.
        isphotoHome = true;

        //        gridview.setBackgroundResource(R.drawable.background);
        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                // Initialize the current position of photo just clicked.
                curPhotoPosition = position;

                //                showImage(curPhotoPosition);
                clickPhotoHandler();

                // Set the flag, now is not in photohome.
                isphotoHome = false;
            }
        });
    }

    private void init() {
        imageList = null;

        imageList = getSD(imagePath, imageList);
        count = imageList.size();

        if (count == 0) {
            Toast.makeText(HelloGridView.this, "No images!!!", Toast.LENGTH_SHORT).show();
        }

        screenWidth = this.getWindowManager().getDefaultDisplay().getWidth();
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();

    }

    /* (non-Javadoc)
     * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();

        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (x < (screenWidth / 2)) {
                curPhotoPosition = curPhotoPosition - 1;
            } else {
                curPhotoPosition = curPhotoPosition + 1;
            }
            clickPhotoHandler();
        }
        return super.onTouchEvent(event);
    }

    /**
     * Handle onclick on the zoom image, Link to next photo when click on the image
     * @param v
     */
    // If reaches the last image, back to the first one.
    public void clickPhotoHandler() {
        if (curPhotoPosition >= count) {
            curPhotoPosition = 0;
        }

        // If reaches the first image, goto the last one.
        if (curPhotoPosition < 0) {
            curPhotoPosition = count - 1;
        }

        // Show the note when reaches the last image
        if (curPhotoPosition == 0) {
            Toast.makeText(HelloGridView.this, "First image", Toast.LENGTH_SHORT).show();
        }

        // Show the note when reaches the last image
        if (curPhotoPosition == count - 1) {
            Toast.makeText(HelloGridView.this, "#" + count + " Last image", Toast.LENGTH_SHORT).show();
        }

        showImage(curPhotoPosition);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Handle KEYCODE_BACK button
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!isphotoHome) {
                setContentView(layouthome);
                isphotoHome = true;
            } else {
                imageList = null;
                layoutimage = null;
                finish();
            }
        }

        return false;
    }

    /**
     * Get the fit screen size image
     * @param id - id of image, like R.drawable.sample_0
     * @return BitmapDrawable
     */
    public BitmapDrawable getFitScreenImage(String path) {
        //        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), id);

        if (bitmap != null)
            bitmap.recycle();

        options = new BitmapFactory.Options();
        //    	options.inSampleSize = 2;

        try {
            bitmap = BitmapFactory.decodeFile(path, options);
        } catch (OutOfMemoryError err) {
            System.out.println(err.toString());
        }

        //    	Bitmap bitmap= BitmapFactory.decodeFile(path,options);
        //        Bitmap bitmap = BitmapFactory.decodeFile(path);

        // Get the width & height of image
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // Calculate the zoom rate
        float scaleWidth = ((float) screenWidth) / width;
        float scaleHeight = ((float) screenHeight) / height;

        // Create the matrix object
        Matrix matrix = new Matrix();

        //        // Add control to keep shape of image - DO NOT DELETE!!!
        //        float rate = (float) height / (float) width;
        //
        //        if (scaleWidth > scaleHeight) {
        //            scaleWidth = (screenHeight * rate / width);
        //            matrix.postScale(scaleWidth, scaleHeight);
        //        } else {
        //            scaleHeight = (screenWidth * rate / height);
        //            matrix.postScale(scaleWidth, scaleHeight);
        //        }

        // Zooming the image...
        matrix.postScale(scaleWidth, scaleHeight);

        // Recreate image
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);

        BitmapDrawable bd = new BitmapDrawable(resizedBitmap);
        bd.setTileModeXY(TileMode.CLAMP, TileMode.CLAMP);
        bd.setDither(true);

        return bd;
    }

    /**
     * Get images from SDcard path.
     * @return
     */
    private static List<String> getSD(String imagePath, List<String> li) {

        if (li == null) {
            li = new ArrayList<String>();
        }

        // Set the reading path of images.
        //        List<String> it = new ArrayList<String>();
        File f = new File(imagePath);

        if (!f.isDirectory()) {
            return li;
        }

        //        File[] files = f.listFiles();
        String[] files = f.list();

        for (int i = 0; i < files.length; i++) {
            //                        File file = files[i];
            File readfile = new File(imagePath + File.separator + files[i]);

            // Skip all thumbnails
            if (readfile.toString().contains("thumbnails")) {
                continue;
            }

            if (!readfile.isDirectory()) {
                if (getImageFile(readfile.getPath()))
                    li.add(readfile.getPath());
            } else {
                getSD(readfile.toString(), li);
            }
        }
        return li;
    }

    /**
     * Get only image file like: *.jpg, *.gif, *.png, *.jpeg, *,bmp
     * @param fName
     * @return
     */
    private static boolean getImageFile(String fName) {
        boolean re;

        //Get the file extensions.
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();

        if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) {
            re = true;
        } else {
            re = false;
        }
        return re;
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onConfigurationChanged(android.content.res.Configuration)
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        screenWidth = this.getWindowManager().getDefaultDisplay().getWidth();
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();

        if (!isphotoHome) {
            //            showImage(curPhotoPosition);
            clickPhotoHandler();
        }

        super.onConfigurationChanged(newConfig);
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(groupPhoto, menuSetWallpaper, Menu.NONE, "Set to wallpaper");
        menu.add(groupPhoto, menuDelete, Menu.NONE, "Delete this image...");
        menu.add(groupHome, menuAbout, Menu.NONE, "About");
        menu.add(groupHome, 4, Menu.NONE, "Test2");
        menu.add(groupHome, 5, Menu.NONE, "Test3");

        return super.onCreateOptionsMenu(menu);
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (!isphotoHome) {
            menu.setGroupVisible(groupHome, false);
            menu.setGroupVisible(groupPhoto, true);
        } else {
            menu.setGroupVisible(groupHome, true);
            menu.setGroupVisible(groupPhoto, false);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case menuSetWallpaper:
                try {
                    this.getApplicationContext().setWallpaper(bitmap);
                    Toast.makeText(HelloGridView.this, "Done!", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case menuDelete:
                File F = new File(imageList.get(curPhotoPosition));
                if (F.delete()) {
                    Log.e(TAG, "DELETE image succeed: " + imageList.get(curPhotoPosition));
                    Toast.makeText(HelloGridView.this, imageList.get(curPhotoPosition) + " was deleted!!!",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(HelloGridView.this, "Failed to delete image!!!", Toast.LENGTH_SHORT).show();
                }

                //Show the image before 
                curPhotoPosition = curPhotoPosition - 1;
                init();
                if (count > 0) {
                    clickPhotoHandler();
                    onResume();
                } else {
                    finish();
                }
                break;
            case menuAbout:
                Toast.makeText(HelloGridView.this, "APP by tjittty", Toast.LENGTH_SHORT).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void showImage(int position) {
        ImageView image = (ImageView) layoutimage.findViewById(R.id.image);
        image.setImageDrawable(getFitScreenImage(imageList.get(position)));
        setContentView(layoutimage);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e(TAG, "start onStart~~~");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e(TAG, "start onRestart~~~");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "start onResume~~~");

        //reload the imageList in gridview when delete the image.
        imageAdapter = new ImageAdapter(this, imageList);
        gridview.setAdapter(imageAdapter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "start onPause~~~");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "start onStop~~~");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "start onDestroy~~~");
    }

}
